package com.config;

import com.entity.Answer;
import net.sf.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 文件上传拦截器
 * @ClassName: FileUploadInterceptor
 * @Description:
 * @author weiyb
 * @date 2018年5月7日 上午11:51:53
 */


public class FileUploadInterceptor implements HandlerInterceptor {
	/*
	 * 视图渲染之后的操作
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	/*
	 * 处理请求完成后视图渲染之前的处理操作
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {

	}

	/*
	 * 进入controller层之前拦截请求
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		Answer answer = new Answer();
		String token =  request.getHeader("TOKEN");
		HttpSession session = request.getSession();
		String sessionToken = (String) session.getAttribute("token");
	//	if(token == null || token.equals("") || sessionToken == null || !sessionToken.equals(token)){
		if(token == null || token.equals("")){
		//if (false){
			answer.setCode(401);
			response.getWriter().println(JSONObject.fromObject(answer));
			return false;
		}else{
			session.setMaxInactiveInterval(60*60*24);
            return true;
        }

	}

}



